<template>
  <div class="container">
    <el-dialog
      title="新增目录"
      width="400px"
      :visible="showDialog"
      @close="btnCancel"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item v-if="!subjectID123" label="所属学科" prop="subjectID">
          <el-select
            v-model="form.subjectID"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in items"
              :label="item.subjectName"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="form.directoryName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="end">
            <el-button @click="btnCancel">取消</el-button>
            <el-button type="primary" @click="btnOk">确定</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys.js'
import { subjectsList } from '@/api/hmmm/subjects.js'
export default {
  name: 'directorys-add',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    subjectID123: {
      type: Number
    }
  },
  data () {
    return {
      items: [],
      form: {
        subjectID: '', // 目录Id
        directoryName: '' // 目录名称

      },
      rules: {
        subjectID: [{ required: true, trigger: 'blur', message: '必选' }],
        directoryName: [{ required: true, message: '目录名称必填', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.subjectsList()
  },
  methods: {
    showDetail (row) {
      this.form = { ...row }
    },
    // 获取所有学科
    async subjectsList () {
      const { data } = await subjectsList()
      this.items = data.items
    },
    // 新增
    async btnOk () {
      if (this.subjectID123) {
        this.form.subjectID = this.subjectID123
      }
      await this.$refs.form.validate()
      if (this.form.id) {
        try {
          await update(this.form)
          this.$message.success('编辑成功')
          this.$refs.form.resetFields()
        } catch (error) {
          console.log(error)
        }
      } else {
        console.log(1)
        try {
          await add(this.form)
          this.$message.success('添加成功')
        } catch (error) {
          console.log(error)
        }
      }
      this.$emit('directorys')
      await this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
      this.$refs.form.resetFields()
    },
    btnCancel () {
      this.form = {
        subjectID: '', // 目录Id
        directoryName: '' // 目录名称
      }
      this.$emit('update:showDialog', false)
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped lang='less'></style>
